package org.yray.javacpp.audio;

import org.yray.javacpp.format.WavFile;

import javax.sound.sampled.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MicDemo {

    public static void main(String[] args) throws LineUnavailableException, InterruptedException, IOException {
        System.out.println("Searching for microphones");
        List<Mixer> mixerList=new ArrayList<>();
        for(Mixer.Info mixerinfo : AudioSystem.getMixerInfo()) {
            Mixer mixer = AudioSystem.getMixer(mixerinfo);
            System.out.println("mixerinfo="+mixerinfo.toString());
            if( mixer.isLineSupported(Port.Info.MICROPHONE) ) {
                mixerList.add(mixer);
                System.out.println("Supported"+Integer.toString(mixerList.size()) + ": " + mixerinfo.toString());
            }
        }

        RecordSound recordSound=new RecordSound();
        Thread thread=new Thread(recordSound);
        thread.start();
        Thread.sleep(10000);
        recordSound.stop();
        String fileName="D:\\test\\mic.wav";
        recordSound.save(fileName);


    }

    public static class RecordSound implements Runnable{

        private boolean stopped=false;
        private ByteArrayOutputStream out;

        @Override
        public void run() {
            TargetDataLine line;
            AudioFormat format=new AudioFormat(8000,16,1,true,false);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
            try {
                line = (TargetDataLine) AudioSystem.getLine(info);
                line.open(format);
                out  = new ByteArrayOutputStream();
                int numBytesRead;
                byte[] data = new byte[line.getBufferSize() / 5];
                // Begin audio capture.
                line.start();
                // Here, stopped is a global boolean set by another thread.
                while (!stopped) {
                    // Read the next chunk of data from the TargetDataLine.
                    numBytesRead =  line.read(data, 0, data.length);
                    // Save this chunk of data.
                    out.write(data, 0, numBytesRead);
                    //System.out.println(Arrays.toString(data));
                }
            } catch (LineUnavailableException e) {
                e.printStackTrace();
            }

        }

        public void stop()
        {
            stopped=true;
        }

        public void save(String fileName) throws IOException {
            byte[] bs=out.toByteArray();
            out.close();
            WavFile wavFile=new WavFile(fileName);
            wavFile.write(bs);
            wavFile.writeFileLen(bs.length);
            wavFile.close();
        }
    }
}
